package com.wjw.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wjw.bean.AjaxResult;
import com.wjw.bean.Page;
import com.wjw.bean.Role;
import com.wjw.bean.User;
import com.wjw.dao.RoleDao;

@Controller
@RequestMapping("role")
public class RoleController {
	@Autowired
	private RoleDao roledao;
	
	@RequestMapping("index")
	public String index(@RequestParam(required=false,defaultValue="1")Integer pagenum,
						@RequestParam(required=false,defaultValue="2")Integer pagesize,Model model){
			
			Map<String, Object> map=new HashMap<>();
			map.put("start", pagenum);
			map.put("size", pagesize);
			List<Role> roles=roledao.pagefind(map);
			model.addAttribute("roles",roles);
		return "role/index";
	}
	
	@RequestMapping("pagefind")
	@ResponseBody
	public Object ajaxpagefind(String searchtext,Integer pagenum,Integer pagesize,Model model){
		AjaxResult ar=new AjaxResult();
		Page<Role> pageuser=new Page<>();
		try {
			Map<String,Object> mp=new HashMap();
			mp.put("start", (pagenum-1)*pagesize);
			mp.put("size", pagesize);
			mp.put("searchtext", searchtext);
			List<Role> lu=roledao.pagefind(mp);
			int pageNo=roledao.findPageNum(mp);
			int pageMax=0;
			if(pageNo%pagesize==0){
				pageMax=pageNo/pagesize;
			}else{
				pageMax=pageNo/pagesize+1;
			}
			
			pageuser.setDatas(lu);
			pageuser.setPageno(pagenum);
			pageuser.setTotalsize(pageNo);
			pageuser.setTotalno(pageMax);
			System.out.println(pageuser.getTotalno());
			ar.setData(pageuser);
			ar.setSuccess(true);
		} catch (Exception e) {
			ar.setSuccess(false);
			e.printStackTrace();
		}
		System.out.println(pageuser.getTotalno());
		return ar;
	}
	
	@RequestMapping("assign")
	public String assign(){
		return "role/assign";
	}
	
	@RequestMapping("doAssign")
	@ResponseBody
	public Object doassign(Integer roleid,Integer[] permissionids){
		AjaxResult ar=new AjaxResult();
		try {
			Map<String, Object> map=new HashMap<>();
			map.put("roleid", roleid);
			map.put("permissionids", permissionids);
			roledao.delPermissions(map);
			roledao.insertRolePer(map);
			ar.setSuccess(true);
		} catch (Exception e) {
			ar.setSuccess(false);
			e.printStackTrace();
		}
		return ar;
	}
}
